package org.robot.scm.platform.server.common;

import java.util.Date;
import org.apache.commons.lang3.StringUtils;
import org.robot.scm.infra.LocalCacheHelper;
import org.robot.scm.pojos.platform.LoggerInfo;
import org.robot.scm.utils.DateTool;
import org.robot.scm.utils.JsonHelper;

/**
 * @Author : Awn create on 2024/5/23 15:47
 */
public class RunnerLogHelper {

    public static void clearLog(String key) {
        LocalCacheHelper.remove(key);
    }

    /**
     * 换行输出
     */
    public static void appendLog(String key, String name, String log) {
        if (StringUtils.isBlank(log)) {
            LoggerInfo localLogger = LoggerInfo.builder().logName(name).timestamp(System.nanoTime()).content("").build();
            LocalCacheHelper.append(key, JsonHelper.toJSONString(localLogger));
            return;
        }
        String dateTime = DateTool.format(new Date(), DateTool.PATTERN_8);
        String regLog = log.replaceAll("[\r\n]+", "");
        LoggerInfo localLogger = LoggerInfo.builder()
                .logName(name)
                .timestamp(System.nanoTime())
                .content(dateTime.concat(" ").concat(regLog))
                .build();
        LocalCacheHelper.append(key, JsonHelper.toJSONString(localLogger));
    }

    /**
     * 换行输出
     */
    public static void appendStartLog(String key, String log) {
        appendLog(key, "main-thread-start", log);
    }

    /**
     * 换行输出
     */
    public static void appendEndLog(String key, String log) {
        appendLog(key, "main-thread-end", log);
    }

    /**
     * 换行输出
     */
    public static void shellLog(String key, String name, String log) {
        if (StringUtils.isBlank(log)) {
            LoggerInfo localLogger = LoggerInfo.builder()
                    .logName(name)
                    .timestamp(System.nanoTime())
                    .content("")
                    .build();
            LocalCacheHelper.append(key, JsonHelper.toJSONString(localLogger));
            return;
        }
        String regLog = log.replaceAll("[\r\n]+", "");
        LoggerInfo localLogger = LoggerInfo.builder()
                .logName(name)
                .timestamp(System.nanoTime())
                .content(regLog)
                .build();
        LocalCacheHelper.append(key, JsonHelper.toJSONString(localLogger));
    }

}
